'use strict';

var async = require('async');
var roleService = require('./roleService.js');
var skillService = require('./skillService.js');
var buildService = require('./buildService.js');
var soldierService = require('./soldierService.js');
var techService = require('./techService.js');
var PlayerManager = require('../libs/playerManager');
var Code = require('../consts/code.js');

exports.updByIdMainPower = function (role_id, player_manager, next) {
    var self = this;
    if (!player_manager) {
        player_manager = new PlayerManager(role_id);
    }
    async.waterfall(
        [
            function (cb) {
                player_manager.getModel(
                    ['role', 'skill', 'build', 'soldier', 'tech', 'accrued'],
                    cb
                );
            },
            function (cb) {
                // 刷新总战力
                self.updateMainPower(player_manager);
                player_manager.save();

                cb();
            }
        ],
        function (err) {
            if (!!next) {
                if (!!err) {
                    console.error(err);
                    return next(null, {
                        code: Code.FAIL
                    });
                }

                return next(null, {
                    code: Code.OK
                });
            }
        }
    );
};

/**
 * 刷新主战力
 */
exports.updateMainPower = function (player_manager) {
    var role_model = player_manager.role;
    var skill_model = player_manager.skill;
    var build_model = player_manager.build;
    var soldier_model = player_manager.soldier;
    var tech_model = player_manager.tech;
    role_model.main_power =
        role_model.hero_power +
        skill_model.skill_power +
        build_model.build_power +
        soldier_model.soldier_power +
        tech_model.tech_power;
};

exports.initFightPower = function (player_manager) {
    roleService.updateHeroPower(player_manager, true);
    skillService.updateSkillPower(player_manager, true);
    buildService.updateBuildPower(player_manager, true);
    soldierService.updateSoldierPower(player_manager, true);
    techService.updateTechPower(player_manager.tech, true);

    this.updateMainPower(player_manager);
};
